<?php
// +----------------------------------------------------------------------
// | @filename ArrayHelper.php
// +----------------------------------------------------------------------
// | @author 落花轻舞问君愁 <mwcx1990@qq.com>
// +----------------------------------------------------------------------
// | @datetime 2021-11-01 13:45:00
// +----------------------------------------------------------------------
// | @Description
// +----------------------------------------------------------------------

namespace Addons\Backend\Helpers;


class ArrayHelper
{
    /**
     * 把二维数组转化为树状结构数组
     * @param array $arr 要处理的数组
     * @param int $pid 父级ID的值，默认是0
     * @param string $idName id的名称,默认是id
     * @param string $pidName pid的名称,默认是pid
     * @return  array    $tree          生成的树状数组
     */
    public static function makeTree($arr = [], $pid = 0, $idName = 'id', $pidName = 'pid', $childName = 'children'): array
    {
        $tree = [];
        foreach ($arr as $k => $v) {
            if ($v[$pidName] == $pid) {
                $tmp = $arr[$k];
                unset($arr[$k]);
                $tmp[$childName] = self::makeTree($arr, $v[$idName], $idName, $pidName, $childName);
                if(empty($tmp[$childName])){
                    unset($tmp[$childName]);
                }
                $tree[] = $tmp;
            }
        }
        return $tree;
    }
}
